﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Web.Mvc;

using CloudSoft.Workflows;

using ERPStore.Extensions;	

namespace ERPStore.Indexers.Lucene.Workflows.Activities
{
	public sealed class GetProductList : CodeActivity
	{
		public InArgument<int> Index { get; set; }
		public InArgument<int> PageSize { get; set; }

		public OutArgument<IList<ERPStore.Models.Product>> ProductList { get; set; }
		public OutArgument<int> ProductCount { get; set; }

		protected override void Execute(CodeActivityContext context)
		{
			int index = context.GetValue(this.Index);
			int pageSize = context.GetValue(this.PageSize);

			var catalogService = context.GetService<ERPStore.Services.ICatalogService>();
			if (catalogService.Name == "Lucene")
			{
				// Pour attaquer la base de données obligatoirement
				catalogService = ((Services.CatalogService)catalogService).GetConnectorCatalogService();
			}
			var count = 0;

			var retryCount = 0;
			IList<ERPStore.Models.Product> list = null;
			string errorMessage = null;
			while (true)
			{
				try
				{
					list = catalogService.GetProductList(index, pageSize, out count);
					context.ReportProgress(count, index, pageSize, string.Format("process products {0}/{1}", Math.Min(count, ((index + 1) * pageSize)), count));
					break;
				}
				catch (Exception ex)
				{
					context.ReportProgress(ex.Message);
					errorMessage = ex.Message;
				}

				if (retryCount > 3)
				{
					var ex = new Exception("Buil Catalog Failed");
					ex.Data.Add("PageIndex", index);
					ex.Data.Add("PageSize", pageSize);
					ex.Data.Add("Message", errorMessage);
					throw ex;
				}

				// On calme le jeu
				System.Threading.Thread.Sleep(1000 * 60);
				retryCount++;
			}

			if (list == null)
			{
				// Pour matcher la condition de sortie du while
				list = new List<ERPStore.Models.Product>();
			}

			// Annulation de l'indexation
			if (context.IsCancelRequested())
			{
				list = new List<ERPStore.Models.Product>();
				count = index * pageSize;
			}

			context.SetValue(ProductList, list);
			context.SetValue(ProductCount, count);
		}
	}
}
